<template>
  <view class="publish-page">

    <!-- 内容输入 -->
    <view class="content-section">
      <textarea 
        v-model="content"
        placeholder="分享你遇到的不良商家或不公平事件..."
        class="content-input"
        maxlength="2000"
        :show-count="true"
      ></textarea>
    </view>

    <!-- 图片选择 -->
    <view class="images-section">
      <view class="images-grid">
        <view 
          v-for="(image, index) in imageList" 
          :key="index"
          class="image-item"
        >
          <image :src="getFullImageUrl(image)" mode="aspectFill" class="image"></image>
          <view class="delete-btn" @click="removeImage(index)">
            <text class="iconfont">&#xe60f;</text>
          </view>
        </view>
        
        <!-- 添加图片按钮 -->
        <view 
          v-if="imageList.length < 9" 
          class="add-image-btn"
          @click="chooseImage"
        >
          <text class="iconfont">&#xe61c;</text>
          <text class="text">添加图片</text>
        </view>
      </view>
      <view class="image-tip">
        <text>最多可上传9张图片，每张不超过5MB</text>
      </view>
    </view>

    <!-- 底部发布按钮 -->
    <view class="bottom-publish-btn">
      <button 
        class="publish-button" 
        :disabled="!canPublish"
        @click="publishPost"
      >
        {{ uploading ? uploadingText : '发布曝光' }}
      </button>
    </view>

    <!-- 加载遮罩 -->
    <view v-if="uploading" class="loading-mask">
      <view class="loading-content">
        <view class="loading-spinner"></view>
        <text>{{ uploadingText }}</text>
      </view>
    </view>
  </view>
</template>

<script>
import api from '@/utils/api.js'

export default {
  data() {
    return {
      content: '',
      imageList: [],
      uploading: false,
      uploadingText: '上传中...'
    }
  },
  computed: {
    canPublish() {
      return this.content.trim().length > 0 && !this.uploading
    }
  },
  methods: {
    // 选择图片
    chooseImage() {
      const maxCount = 9 - this.imageList.length
      
      uni.chooseImage({
        count: maxCount,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          this.uploadImages(res.tempFilePaths)
        }
      })
    },
    
    // 上传图片
    async uploadImages(filePaths) {
      this.uploading = true
      this.uploadingText = '上传图片中...'
      
      try {
        const uploadPromises = filePaths.map(filePath => this.uploadSingleImage(filePath))
        const results = await Promise.all(uploadPromises)
        
        // 过滤成功的上传结果
        const successResults = results.filter(result => result && result.images)
        const newImages = successResults.flatMap(result => result.images)
        
        this.imageList = [...this.imageList, ...newImages]
        
        if (successResults.length < filePaths.length) {
          uni.showToast({
            title: '部分图片上传失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('图片上传失败:', error)
        uni.showToast({
          title: '图片上传失败',
          icon: 'none'
        })
      } finally {
        this.uploading = false
      }
    },
    
    // 上传单张图片
    uploadSingleImage(filePath) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: api.getBaseURL() + '/exposure/upload',
          filePath: filePath,
          name: 'images',
          header: {
            'Authorization': `Bearer ${uni.getStorageSync('token')}`
          },
          success: (uploadRes) => {
            try {
              const response = JSON.parse(uploadRes.data)
              if (response.success) {
                resolve(response.data)
              } else {
                reject(new Error(response.message || '上传失败'))
              }
            } catch (error) {
              console.error('解析上传响应失败:', error, uploadRes.data)
              reject(error)
            }
          },
          fail: reject
        })
      })
    },
    
    // 删除图片
    removeImage(index) {
      this.imageList.splice(index, 1)
    },
    
    // 发布帖子
    async publishPost() {
      if (!this.canPublish) return
      
      this.uploading = true
      this.uploadingText = '发布中...'
      
      try {
        const response = await api.request({
          url: '/exposure/posts',
          method: 'POST',
          data: {
            content: this.content.trim(),
            images: this.imageList
          }
        })
        
        if (response.success) {
          uni.showToast({
            title: '发布成功',
            icon: 'success'
          })
          
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        }
      } catch (error) {
        uni.showToast({
          title: error.message || '发布失败',
          icon: 'none'
        })
      } finally {
        this.uploading = false
      }
    },
    
    // 获取完整图片URL
    getFullImageUrl(imagePath) {
      if (!imagePath) return ''
      if (imagePath.startsWith('http')) return imagePath
      return api.getBaseURL().replace('/api/v1', '') + imagePath
    },
    
    // 返回
    goBack() {
      if (this.content.trim() || this.imageList.length > 0) {
        uni.showModal({
          title: '确认离开',
          content: '你还有未发布的内容，确定要离开吗？',
          success: (res) => {
            if (res.confirm) {
              uni.navigateBack()
            }
          }
        })
      } else {
        uni.navigateBack()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.publish-page {
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.content-section {
  background-color: #fff;
  margin-bottom: 20rpx;
  flex: 1;
  
  .content-input {
    width: 100%;
    min-height: 300rpx;
    padding: 30rpx;
    font-size: 30rpx;
    line-height: 1.6;
    box-sizing: border-box;
  }
}

.images-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 120rpx;
  
  .images-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
  }
  
  .image-item {
    position: relative;
    width: 200rpx;
    height: 200rpx;
    
    .image {
      width: 100%;
      height: 100%;
      border-radius: 8rpx;
    }
    
    .delete-btn {
      position: absolute;
      top: -10rpx;
      right: -10rpx;
      width: 40rpx;
      height: 40rpx;
      background-color: #ff4757;
      color: #fff;
      border-radius: 20rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24rpx;
    }
  }
  
  .add-image-btn {
    width: 200rpx;
    height: 200rpx;
    border: 2rpx dashed #ccc;
    border-radius: 8rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #999;
    
    .iconfont {
      font-size: 48rpx;
      margin-bottom: 10rpx;
    }
    
    .text {
      font-size: 24rpx;
    }
  }
  
  .image-tip {
    margin-top: 20rpx;
    font-size: 24rpx;
    color: #999;
  }
}

.bottom-publish-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 30rpx;
  border-top: 1rpx solid #eee;
  
  .publish-button {
    width: 100%;
    height: 88rpx;
    background-color: #007AFF;
    color: #fff;
    border-radius: 8rpx;
    font-size: 32rpx;
    font-weight: bold;
    border: none;
    
    &:disabled {
      background-color: #ccc;
      color: #999;
    }
    
    &:not(:disabled):active {
      background-color: #0056cc;
    }
  }
}

.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  
  .loading-content {
    background-color: #fff;
    padding: 40rpx;
    border-radius: 10rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .loading-spinner {
      width: 60rpx;
      height: 60rpx;
      border: 4rpx solid #f3f3f3;
      border-top: 4rpx solid #007AFF;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 20rpx;
    }
    
    text {
      font-size: 28rpx;
      color: #333;
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>